package com.zhuhjay.common.core.security.handler;

import cn.hutool.core.util.StrUtil;
import com.zhuhjay.common.base.constant.CacheConstant;
import com.zhuhjay.common.base.constant.SecurityConstant;
import com.zhuhjay.common.base.util.JacksonUtils;
import com.zhuhjay.common.core.util.JwtUtils;
import com.zhuhjay.common.redis.util.RedisUtils;
import com.zhuhjay.common.security.LoginUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZhuHJay
 * @date 2023/3/5 11:13
 */
@Slf4j
public class CustomerLogoutHandler implements LogoutHandler {

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 如果有token, 才能进行登出操作
        String authorization = request.getHeader(SecurityConstant.AUTH_HEADER_KEY);
        if (StrUtil.isBlank(authorization) || !authorization.startsWith(SecurityConstant.AUTH_REQ_TITLE)) {
            return;
        }

        // 查看缓存中是否存在该token
        String token = JwtUtils.exportToken(authorization);
        String uid = RedisUtils.getCache(CacheConstant.TOKEN_PREFIX + token);
        if (uid == null) {
            // token 不存在, 说明已经登出
            return;
        }
        // 清理token缓存
        RedisUtils.deleteCache(CacheConstant.TOKEN_PREFIX + token);

        String infoStr = RedisUtils.getCache(CacheConstant.USER_UNIQUE_ID_PREFIX + uid);
        // 用户被迫下线
        if (StrUtil.isBlank(infoStr)) {
            return;
        }
        // 清理uid缓存
        RedisUtils.deleteCache(CacheConstant.USER_UNIQUE_ID_PREFIX + uid);

        LoginUserDetail loginUserDetail = JacksonUtils.readValue(infoStr, LoginUserDetail.class);
        // 用户在线缓存删除
        RedisUtils.removeValue4Set(CacheConstant.USER_ONLINE_PREFIX + loginUserDetail.getUsername(), uid);
    }

}
